//
//  QDPayTypeViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/28.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 绑定支付方式下方的小字
final class QDPayTypeFooterView: UIView {
    
    /// 高度
    lazy var height: CGFloat = {
       
        let size = CGSize(width: UIScreen.main.ritl_width - 40, height: 100)
        let sub1Height = self.subtitleLabel1.textRect(forBounds: CGRect(origin: .zero, size: size), limitedToNumberOfLines: 0).height
        let sub2Height = self.subtitleLabel2.textRect(forBounds: CGRect(origin: .zero, size: size), limitedToNumberOfLines: 0).height

        return sub1Height + sub2Height + 22 + 25 + 20 + 10
    }()
    
    /// 显示温馨提示
    let titleLabel = UILabel()
    /// 显示第一条
    let subtitleLabel1 = UILabel()
    /// 显示第二条
    let subtitleLabel2 = UILabel()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        titleLabel.font = Font.regular.font(size: 16)
        titleLabel.textColor = 179.ritl_color
        titleLabel.text = "温馨提示"
        
        subtitleLabel1.font = Font.regular.font(size: 14)
        subtitleLabel1.textColor = 179.ritl_color
        subtitleLabel1.numberOfLines = 0
        subtitleLabel1.text = "1.绑定完成后，需将一个绑定渠道设置为支付渠道，方可通过该渠道进行扣费。"
        
        subtitleLabel2.font = Font.regular.font(size: 14)
        subtitleLabel2.textColor = 179.ritl_color
        subtitleLabel2.numberOfLines = 0
        subtitleLabel2.text = "2.签约渠道的解绑周期为4天左右，解绑期间无法通过该渠道扣费。"
        
        addSubview(titleLabel)
        addSubview(subtitleLabel1)
        addSubview(subtitleLabel2)
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(25)
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(22)
        }
        
        subtitleLabel1.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20).priority(.high)
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
        }
        
        subtitleLabel2.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20).priority(.high)
            make.top.equalTo(subtitleLabel1.snp.bottom).offset(10)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


private extension QDPayTypeModel.QDPaySignType {
    
    /// 支付类型状态的背景图
    var payTypeStatusImage: UIImage? {
        switch self {
        case .canceling: return "pt_release_gb".namedImage
        default: return nil
        }
    }
}


/// 绑定支付方式
final class QDPayTypeViewController: NWTableViewController {
    
    ///数据源
    var titles = [["微信支付","支付宝支付"],["银联支付"]]
    var headerTitles = ["已绑定支付方式","可绑定支付方式"]
    
    
    /// 所有的支付方式
    private var allPayTypes = [QDPayTypeModel]() {
        willSet {
            
            /// 所有的签约类型
            let signTypes = newValue.filter { $0.signStatusType != .nothing }
            
            //重新按照默认在前的顺序排序
            bindingPayTypes = signTypes.filter{ $0.defaultChannel } + signTypes.filter { !$0.defaultChannel }
            
            unBindPayTypes = newValue.filter { $0.signStatusType == .nothing }
            tableView.reloadData()
        }
    }
    /// 所有绑定过的支付方式
    private var bindingPayTypes = [QDPayTypeModel]()
    /// 所有没有绑定过的支付方式
    private var unBindPayTypes = [QDPayTypeModel]()
    /// 作为数据源的方式
    private var dataPayTypes:[[QDPayTypeModel]] {
        get {
            return [bindingPayTypes,unBindPayTypes]
        }
    }
    
    
    /**  2019-05-07 开始去除不必要的header   **/
    
    /// 是否已经存在绑定的支付方式
    private var hasBindingPayTypes: Bool {
        return !bindingPayTypes.isEmpty
    }
    
    /// 是否存在未绑定的支付方式
    private var hasUnBindingPayTypes: Bool {
        return !unBindPayTypes.isEmpty
    }
    
    /// section的个数
    private var sectionCount: Int {
        if hasBindingPayTypes && hasUnBindingPayTypes {//如果都存在，返回2
            return 2
        }
        return 1
    }
    
    /// headerTitle
    private func headerTitle(in section: Int) -> String {
        
        if hasBindingPayTypes && hasUnBindingPayTypes {//如果都存在，返回2
            return headerTitles[section]
        }
        
        //只存在未绑定的
        if hasUnBindingPayTypes {
            return headerTitles[1]
        }
        
        return headerTitles[0]
    }
    
    /// row的个数
    private func rowNumber(in section: Int) -> Int {
        if hasBindingPayTypes && hasUnBindingPayTypes {//如果都存在，返回2
            return dataPayTypes[section].count
        }
        
        //只存在未绑定的
        if hasUnBindingPayTypes {
            return unBindPayTypes.count
        }
        
        return bindingPayTypes.count
    }
    
    
    /// 获得当前位置的payModel
    private func payModels(at indexPath: IndexPath) -> QDPayTypeModel {
        
        if hasBindingPayTypes && hasUnBindingPayTypes {//如果都存在，返回2
            return dataPayTypes[indexPath.section][indexPath.row]
        }
        
        //只存在未绑定的
        if hasUnBindingPayTypes {
            return unBindPayTypes[indexPath.row]
        }
        
        return bindingPayTypes[indexPath.row]
    }
    
    
    
    
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
    
        footerRefreshEnable = false
        tableView.rowHeight = 92
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        navigationItem.title = "绑定支付方式"
        
        //footerView
        let footerView = QDPayTypeFooterView(frame: CGRect(origin: .zero, size: CGSize(width: ritl_width, height: 0)))
        footerView.ritl_height = footerView.height
        tableView.tableFooterView = footerView
        
        //追加通知
        NotificationCenter.default.addObserver(self, selector: #selector(requestPayTypes), name: QDPayTypeStatusDidChangedNotificationName, object: nibName)
        //请求
        requestPayTypes()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDPayTypeTableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.register(QDPayTypeHeaderView.self, forHeaderFooterViewReuseIdentifier: "headerView")
    }
    
    override func headerRefreshBeginHandler() {
        requestPayTypes()
    }
}


extension QDPayTypeViewController {
    
    /// 请求支付方式
    @objc func requestPayTypes(){
        
        view.showWatingHUD()
        QDNetworkingManager.requestPayTypeList(complete: { (payTypes, _, _) in
            
            self.endHeaderRefreshing()
            self.view.dismissHUD()
            self.allPayTypes = payTypes
            
        }) { (msg, errorType) in
            self.view.showTextHUD(text: msg)
        }
    }
}




extension QDPayTypeViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return sectionCount
//        return dataPayTypes.count
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rowNumber(in: section)
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        /// 为绑定方式进行单独设置
        if let typeCell = cell as? QDPayTypeTableViewCell {
            
            /// 支付类型
            let payType = payModels(at: indexPath)
            
            /// 设置 xxx 支付
            typeCell.titleLabel.text = payType.type.payTypeTitle
            typeCell.headerImageView.image = payType.type.payTypeImage.namedImage
            typeCell.subtitleLabel.text = payType.discountMsg
            //如果是默认
            if payType.defaultChannel {
                typeCell.statusImageView.isHidden = false
                typeCell.statusImageView.image = "pt_default_bg".namedImage
                typeCell.statusLabel.text = "默认支付"
                
            }else if payType.signStatusType == .canceling {//如果是解绑中
                typeCell.statusImageView.isHidden = false
                typeCell.statusImageView.image = "pt_release_gb".namedImage
                typeCell.statusLabel.text = "解绑中"
            }else {
                typeCell.statusImageView.isHidden = true
                typeCell.statusLabel.text = nil
            }
        }
        
        return cell
    }
    
    
    /// headerView
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerView")
        
        if let typeHeader = headerView as? QDPayTypeHeaderView {
            typeHeader.titleLabel.text = headerTitle(in: section)
        }
        
        return headerView
    }
    
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 50 : 56
    }
    
    
    
    /// 点击进行绑定
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        /// 获得方式
        let payModel = payModels(at: indexPath)
        
        /// 跳转到设置控制器
        func pushToPayTypeSettingViewController(){
            
            // 设置
            navigationController?.pushViewController(QDPayTypeSettingViewController(channelId: payModel.payChannelId, payType: payModel.type, isDefault: payModel.defaultChannel), animated: true)
        }
        
        /// 进行方式签约
        func bindingPayType(){
            
            //获得签约方式:
            let payType = payModel.type
            
            //进行检测
            if payType == .ALiPay && !UIApplication.shared.canOpenURL(URL(string: "alipay://")!) {
                view.showTextHUD(text: "支付宝客户端无法签约"); return
            }
            
            if (payType == .Weixin && !(WXApi.isWXAppInstalled() && WXApi.isWXAppSupport())) {
                view.showTextHUD(text: "微信客户端无法签约"); return
            }
            
            switch payType {//埋点
            case .ALiPay: QDUMEventManager.event(event: .signALi)
            case .Weixin: QDUMEventManager.event(event: .signWeixin)
            case .Union: QDUMEventManager.event(event: .signUnion)
            default: break
            }
            
            
            if payType == .Union { //跳转至实名认证
                let fillViewController = QDUnionFillViewController()
                fillViewController.backViewController = self
                ritl_topNavigationPush(fillViewController, animated: true); return
            }
            
            //开始签约
            QDPaymentSignManager.sharedInstance.sign(type: payType, data:["payChannelCode":payType],delegate: self, viewController: self)
        }
        
        
        switch payModel.signStatusType {
            case .nothing: bindingPayType() //进行绑定
            case .canceling: view.showTextHUD(text: "解绑中") //提示
            case .binding: pushToPayTypeSettingViewController()//如果没有绑定，进行绑定
        }
    }
}


extension QDPayTypeViewController: QDPaymentSignManagerDelegate {
    
    func complete(payType: QDPayType, data: String, id: String) {
        
        //如果是支付宝，打开url:
        if payType == .ALiPay && UIApplication.shared.openURL(URL(string: data)!) {
            //跳出状态界面
            ritl_topNavigationPush(QDPayTypeStatusViewController(channelId: id, payType: payType, backViewController: self), animated: true)
        }
        
        //如果是微信，进行签约
        if payType == .Weixin{
            let req = OpenWebviewReq()
            req.url = data
            if WXApi.send(req){
                //跳出状态界面
                ritl_topNavigationPush(QDPayTypeStatusViewController(channelId: id, payType: payType, backViewController: self), animated: true)
            }
        }
        
    }
    
    
    func fail(error: String) {
        
    }
}
